import datetime

from django.db import models
from django.db.models import Max

from member.models import Retailer
from wxchat.constants import PAY_ORDER_STATUS


class Card(models.Model):
    """制卡"""
    name = models.CharField(verbose_name='卡名称', max_length=64, blank=True, null=True)
    retailer = models.ForeignKey(Retailer, on_delete=models.CASCADE, verbose_name='商家名称', blank=True, null=True, db_constraint=False)
    comment = models.CharField(verbose_name='活动说明', max_length=256, blank=True, null=True)
    begin_date = models.DateField(verbose_name='开始时间', blank=True, null=True)
    end_date = models.DateField(verbose_name='结束时间', blank=True, null=True)
    image = models.ImageField(verbose_name='卡图片', upload_to='cards/', blank=True, null=True)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '品鉴卡'
        verbose_name_plural = verbose_name
        ordering = ["-id"]


class RetailerCard(models.Model):
    """商家卡"""
    ACK = (
        (0, '待确认'),
        (1, '已确认'),
    )
    card = models.ForeignKey(Card, verbose_name='卡名称', on_delete=models.CASCADE, blank=True, null=True)
    retailer = models.ForeignKey(Retailer, on_delete=models.CASCADE, verbose_name='商家名称', blank=True, null=True, db_constraint=False)
    # amount = models. IntegerField(verbose_name='金额',  blank=True, null=True)
    r_openid = models.CharField(verbose_name='商家微信号', max_length=32, blank=True, null=True)
    r_name = models.CharField(verbose_name='商家姓名', max_length=32, blank=True, null=True)
    c_openid = models.CharField(verbose_name='授权方微信号', max_length=32, blank=True, null=True)
    c_name = models.CharField(verbose_name='授权方姓名', max_length=32, blank=True, null=True)
    comment = models.CharField(verbose_name='使用说明', max_length=256, blank=True, null=True)
    ack = models.IntegerField(verbose_name='确认', blank=True, null=True, choices=ACK)
    count = models.IntegerField(verbose_name='数量', blank=True, null=True)
    key = models.CharField(verbose_name='授权Key', max_length=64, blank=True, null=True)
    discount = models.IntegerField(verbose_name='折扣率', blank=True, null=True)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.card.name

    class Meta:
        verbose_name = '商家卡'
        verbose_name_plural = verbose_name
        ordering = ["-id"]


class CardDepositRecord(models.Model):
    """
    用户购买会员卡记录表
    """
    out_trade_no = models.CharField(verbose_name='订单编号', max_length=32)
    name = models.CharField(verbose_name='用户名', max_length=128, blank=True, default='')
    telephone = models.CharField(verbose_name='电话号码', max_length=16, blank=True, null=True, default='')
    retailer = models.ForeignKey(Retailer, verbose_name='商家', blank=True, null=True, db_constraint=False, on_delete=models.DO_NOTHING)
    openid = models.CharField(verbose_name='微信号(openid)', max_length=32)
    transaction_id = models.CharField(verbose_name='微信支付订单号', max_length=32, null=True, blank=True)
    total_fee = models.DecimalField(verbose_name='应收款', max_digits=7, decimal_places=2, blank=True, null=True)
    cash_fee = models.DecimalField(verbose_name='实收款', max_digits=7, decimal_places=2, blank=True, null=True)
    r_card = models.ForeignKey(RetailerCard, verbose_name="商家会员卡", on_delete=models.SET_NULL, blank=True, null=True, db_constraint=False)
    r_count = models.IntegerField(verbose_name='数量', blank=True, null=True)
    pay_time = models.DateTimeField(verbose_name='支付时间', blank=True, null=True)
    status = models.IntegerField(verbose_name='支付状态', default=0, choices=PAY_ORDER_STATUS)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now_add=False, auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True, auto_now=False)

    class Meta:
        verbose_name = '购卡记录表'
        verbose_name_plural = verbose_name
        ordering = ["-id"]

    def __str__(self):
        return self.out_trade_no

    def save(self, *args, **kwargs):
        if not self.id:
            if self.r_card and self.status == 1:
                self.r_card.count += self.r_count
                self.r_card.save()

        return super().save(*args, **kwargs)


class GiftCard(models.Model):
    """赠送卡"""
    STATUS = (
        (0, '取消'),
        (1, '已赠送'),
    )
    order_no = models.CharField(verbose_name='单号', max_length=16, blank=True, null=True)
    retailer = models.ForeignKey(Retailer, verbose_name='商家', blank=True, null=True, on_delete=models.DO_NOTHING, db_constraint=False)
    openid = models.CharField(verbose_name='商家微信ID', max_length=32, blank=True, null=True)
    name = models.CharField(verbose_name='店员', max_length=128, blank=True, null=True)
    branch = models.CharField(verbose_name='分店', max_length=128, blank=True, null=True)
    customer_openid = models.CharField(verbose_name='客户微信ID', max_length=32, blank=True, null=True)
    customer_name = models.CharField(verbose_name='客户姓名', max_length=128, blank=True, null=True)
    r_card = models.ForeignKey(RetailerCard, verbose_name="商家会员卡", on_delete=models.DO_NOTHING, blank=True, null=True,
                               db_constraint=False)
    r_count = models.IntegerField(verbose_name='数量', blank=True, null=True)
    r_unused_count = models.IntegerField(verbose_name='待激活数量', blank=True, null=True)
    order_key = models.CharField(verbose_name='单号key', max_length=64, blank=True, null=True)
    status = models.IntegerField(verbose_name='状态', blank=True, null=True, choices=STATUS)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.openid

    class Meta:
        verbose_name = '赠送卡'
        verbose_name_plural = verbose_name
        ordering = ["-id"]

    @classmethod
    def get_max_code(cls):
        year = datetime.datetime.now().strftime('%Y%m%d')
        max_code = cls.objects.filter(order_no__startswith=year).aggregate(max_code=Max("order_no"))
        max_value = max_code['max_code']
        if max_value is None:
            num = '0001'
            code = '{0}{1}'.format(year, num)
            return code
        else:
            num = str(int(max_value[-4:]) + 1).rjust(4, '0')
            code = '{0}{1}'.format(year, num)
            return code

    def save(self, *args, **kwargs):
        if not self.order_no:
            order_no = self.__class__.get_max_code()
            self.order_no = order_no

        return super().save(*args, **kwargs)


class UserGiftCard(models.Model):
    """客户会员卡"""
    openid = models.CharField(verbose_name='微信ID', max_length=32, blank=True, null=True)
    name = models.CharField(verbose_name='姓名', max_length=128, blank=True, null=True)
    retailer = models.ForeignKey(Retailer, verbose_name='商家', blank=True, null=True, on_delete=models.DO_NOTHING,
                                 db_constraint=False)
    r_card = models.ForeignKey(RetailerCard, verbose_name="商家会员卡", on_delete=models.DO_NOTHING, blank=True, null=True,
                               db_constraint=False)
    r_count = models.IntegerField(verbose_name='数量', blank=True, null=True)
    r_unused_count = models.IntegerField(verbose_name='待激活数量', blank=True, null=True)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.openid

    class Meta:
        verbose_name = '客户会员卡'
        verbose_name_plural = verbose_name
        ordering = ["-id"]


class CardConsumeRecord(models.Model):
    """客户会员卡消费记录"""
    openid = models.CharField(verbose_name='微信ID', max_length=32, blank=True, null=True)
    name = models.CharField(verbose_name='姓名', max_length=128, blank=True, null=True)
    retailer = models.ForeignKey(Retailer, verbose_name='商家', on_delete=models.DO_NOTHING, db_constraint=False, blank=True, null=True)
    r_openid = models.CharField(verbose_name='商家微信ID', max_length=32, blank=True, null=True)
    r_name = models.CharField(verbose_name='员工姓名', max_length=128, blank=True, null=True)
    r_card = models.ForeignKey(RetailerCard, verbose_name="商家会员卡", on_delete=models.DO_NOTHING, blank=True, null=True,
                               db_constraint=False)
    r_count = models.IntegerField(verbose_name='数量', blank=True, null=True)
    comment = models.CharField(verbose_name='消费说明', max_length=256, blank=True, null=True)
    consume_key = models.CharField(verbose_name='消费Key', max_length=64, blank=True, null=True)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '会员卡消费'
        verbose_name_plural = verbose_name
        ordering = ["-id"]


class SampleCard(models.Model):
    """客户品鉴卡"""
    STATUS = (
        (0, "待用"),
        (1, "已用"),
    )
    card = models.ForeignKey(Card, verbose_name="品鉴卡", blank=True, null=True, on_delete=models.CASCADE, db_constraint=False)
    openid = models.CharField(verbose_name="客户微信ID", blank=True, null=True, max_length=32)
    name = models.CharField(verbose_name="客户名称", blank=True, null=True, max_length=128)
    key = models.CharField(verbose_name="MD5码", max_length=64, blank=True, null=True)
    status = models.IntegerField(verbose_name="状态", choices=STATUS, blank=True, default=0)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.openid

    class Meta:
        verbose_name = '客户品鉴卡'
        verbose_name_plural = verbose_name
        ordering = ["-id"]


class ClientSampleRecord(models.Model):
    """客户品鉴记录"""
    FLAG = (
        (0, '待结'),
        (1, '已结'),
    )
    openid = models.CharField(verbose_name='微信ID', max_length=32, blank=True, null=True)
    name = models.CharField(verbose_name='姓名', max_length=128, blank=True, null=True)
    retailer = models.ForeignKey(Retailer, verbose_name='商家', related_name="records", on_delete=models.DO_NOTHING, db_constraint=False, blank=True, null=True)
    r_openid = models.CharField(verbose_name='商家微信ID', max_length=32, blank=True, null=True)
    r_name = models.CharField(verbose_name='商家姓名', max_length=128, blank=True, null=True)
    card = models.ForeignKey(Card, verbose_name="品鉴卡", on_delete=models.DO_NOTHING, blank=True, null=True,
                             db_constraint=False)
    balance_date = models.DateField(verbose_name="结算时间", blank=True, null=True)
    balance_time = models.DateTimeField(verbose_name="结算操作时间", blank=True, null=True)
    balance_flag = models.IntegerField(verbose_name="结算标识", blank=True, default=0, choices=FLAG)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '客户品鉴记录'
        verbose_name_plural = verbose_name
        ordering = ["-id"]


class BalanceBill(models.Model):
    """结算单列表"""
    retailer = models.ForeignKey(Retailer, verbose_name='商家', related_name="bills", on_delete=models.DO_NOTHING, db_constraint=False, blank=True, null=True)
    bill_date = models.DateField(verbose_name="结算时间", blank=True, null=True)
    counts = models.IntegerField(verbose_name="结算数量", blank=True, null=True)
    openid = models.CharField(verbose_name="微信id", max_length=32, blank=True, null=True)
    name = models.CharField(verbose_name="姓名", max_length=64, blank=True, null=True)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '结算单'
        verbose_name_plural = verbose_name
        ordering = ["-id"]
